<route lang="json5">
{
  style: {
    navigationBarTitleText: '修改密码',
  },
}
</route>

<template>
  <view class="profile-info-container">
    <view class="profile-card">
      <view class="form-wrapper">
        <wd-form ref="formRef" :model="formData" :rules="formRules">
          <wd-cell-group class="form-group">
            <view class="sex-field">
              <view class="zh-tb-text form-item-width">
                <text>原密码</text>
                <text>བོད་ཀྱི་སྐད</text>
              </view>
              <view class="flex-1">
                <wd-input
                  prop="oldPassword"
                  clearable
                  v-model="formData.oldPassword"
                  :placeholder="
                    showTibetan ? '请输入原来密码བོད་ཀྱི་སྐདབོད་ཀྱི་སྐད' : '请输入原来密码'
                  "
                  show-password
                  :rules="[{ required: true, message: '请输入原来密码' }]"
                  class="form-input"
                />
              </view>
            </view>
            <view class="sex-field">
              <view class="zh-tb-text form-item-width">
                <text>新密码</text>
                <text>བོད་ཀྱི་སྐད</text>
              </view>
              <view class="flex-1">
                <wd-input
                  prop="newPassword"
                  clearable
                  v-model="formData.newPassword"
                  :placeholder="showTibetan ? '请输入新密码བོད་ཀྱི་སྐདབོད་ཀྱི་སྐད' : '请输入新密码'"
                  show-password
                  :rules="[{ required: true, message: '请输入新密码' }]"
                  class="form-input"
                />
              </view>
            </view>
            <view class="sex-field">
              <view class="zh-tb-text form-item-width">
                <text>确认密码</text>
                <text>བོད་ཀྱི་སྐད</text>
              </view>
              <view class="flex-1">
                <wd-input
                  prop="confirmPassword"
                  clearable
                  v-model="formData.confirmPassword"
                  :placeholder="showTibetan ? '请输入新密码བོད་ཀྱི་སྐདབོད་ཀྱི་སྐད' : '请输入新密码'"
                  show-password
                  :rules="[{ required: true, message: '请输入新密码' }]"
                  class="form-input"
                />
              </view>
            </view>
          </wd-cell-group>
        </wd-form>

        <!-- 操作按钮 -->
        <view class="form-actions">
          <wd-button
            type="primary"
            size="large"
            @click="handleResetPassword"
            custom-class="custom-shadow"
            customStyle=" width: 60vw; height: 6vh "
          >
            <view class="zh-tb-text">
              <text>确认</text>
              <text>བོད་ཀྱི་སྐད</text>
            </view>
          </wd-button>
        </view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { useUserStore } from '@/store'
import { storeToRefs } from 'pinia'
import { toast } from '@/utils/toast'
import { resetPassword } from '@/api/login'
import { showToastAsync } from '@/utils/toast'
import { updateInfo, updateUserPassword } from '@/api/login'

// 表单引用
const formRef = ref()

// 用户信息
const showTibetan = import.meta.env.VITE_SHOW_TIBETAN === 'true'
const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)

// 表单数据
const formData = reactive({
  // id: userInfo.value.id,
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
})
// 验证规则
const formRules: any = {
  oldPassword: [
    {
      required: true,
      message: '请输入密码(བོད་ཀྱི་སྐད་བོད་ཀྱི་སྐད་)',
      trigger: ['blur', 'change'],
    },
    // 正则判断为字母或数字
    // {
    //   pattern: /^[0-9a-zA-Z]*$/g,
    //   // 正则检验前先将值转为字符串
    //   transform(value: any) {
    //     return String(value)
    //   },
    //   message: '只能包含字母或数字',
    // },
    {
      validator: (value: any) => {
        if (value.length >= 5 && value.length <= 12) {
          return Promise.resolve()
        } else {
          return Promise.reject('密码长度必须在5到12位之间')
        }
      },
      trigger: 'blur',
    },
  ],
  newPassword: [
    {
      required: true,
      message: '请输入密码(བོད་ཀྱི་སྐད་བོད་ཀྱི་སྐད་)',
      trigger: ['blur', 'change'],
    },
    // 正则判断为字母或数字
    {
      pattern: /^[0-9a-zA-Z]*$/g,
      // 正则检验前先将值转为字符串
      transform(value: any) {
        return String(value)
      },
      message: '只能包含字母或数字',
    },
    {
      validator: (value: any) => {
        if (value.length >= 5 && value.length <= 12) {
          return Promise.resolve()
        } else {
          return Promise.reject('密码长度必须在5到12位之间')
        }
      },
      trigger: 'blur',
    },
  ],
  confirmPassword: [
    { required: true, message: '确认密码(བོད་ཀྱི་སྐད་བོད་ཀྱི་སྐད་)', trigger: ['blur', 'change'] },
    // 正则判断为字母或数字
    {
      pattern: /^[0-9a-zA-Z]*$/g,
      // 正则检验前先将值转为字符串
      transform(value: any) {
        return String(value)
      },
      message: '只能包含字母或数字',
    },
    {
      validator: (value: any) => {
        if (value.length >= 5 && value.length <= 12) {
          return Promise.resolve()
        } else {
          return Promise.reject('密码长度必须在5到12位之间')
        }
      },
      trigger: 'blur',
    },
    {
      validator: (value: string) => value === formData.newPassword,
      message: '两次密码输入不一致',
      trigger: ['blur', 'change'],
    },
  ],
}
// 提交表单
const handleResetPassword = async () => {
  try {
    // 表单校验
    const { valid, errors } = await formRef.value.validate()
    if (!valid) {
      console.log('表单校验未通过:', errors)
      return // ✅ 校验失败，终止后续代码
    }
    uni.showLoading({
      title: '正在修改密码...',
      mask: true, // 关键：蒙版禁止页面交互
    })
    const res = await resetPassword(formData)
    if (res.code === 0) {
      await showToastAsync('修改密码成功', 1500)

      uni.navigateTo({ url: '/pages/login/index' })
    } else {
      await showToastAsync(res.msg || '修改密码失败', 1500, 'none')
    }
  } catch (error) {
    console.error('注册失败:', error)
  } finally {
    // 7. 无论成功/失败，关闭加载（必须执行）
    uni.hideLoading()
  }
}
</script>

<style lang="scss" scoped>
.profile-info-container {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 30rpx;
}

.profile-card {
  background-color: #ffffff;
  border-radius: 24rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.04);
  overflow: hidden;
}

.card-header {
  padding: 40rpx 30rpx 20rpx;
  border-bottom: 2rpx solid #f0f0f0;
}

.card-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333;
  position: relative;
  display: inline-block;
  padding-bottom: 16rpx;

  &::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    width: 60rpx;
    height: 6rpx;
    background: linear-gradient(90deg, #4a7bff, #6a5acd);
    border-radius: 6rpx;
  }
}

.form-wrapper {
  padding: 20rpx;
}

.form-group {
  border-radius: 16rpx;
  overflow: hidden;
  margin-bottom: 40rpx;
}

.form-input {
  font-size: 30rpx;
}

.sex-field {
  display: flex;
  align-items: center;
  padding: 24rpx 10rpx;
  background-color: #ffffff;
}

.field-label {
  width: 180rpx;
  font-size: 30rpx;
  color: #000;
}

.radio-group {
  flex: 1;
  display: flex;
  gap: 20rpx;
}

.radio-btn {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  font-size: 30rpx;
  border-radius: 12rpx;
  background-color: #f5f7fa;

  &:active {
    opacity: 0.8;
  }
}

.form-actions {
  display: flex;
  flex-direction: row;
  justify-content: center;
  margin-top: 40rpx;
  gap: 20rpx;
}

.submit-btn {
  height: 90rpx;
  border-radius: 45rpx;
  font-size: 32rpx;
  font-weight: 500;
  background: linear-gradient(135deg, #4a7bff, #6a5acd);
  box-shadow: 0 8rpx 16rpx rgba(74, 123, 255, 0.2);
  transition: all 0.3s ease;

  &:active {
    transform: translateY(2rpx);
    box-shadow: 0 4rpx 8rpx rgba(74, 123, 255, 0.15);
  }
}

.custom-shadow {
  width: 60vw;
  display: block;
}
</style>
